package top.xin1901.j2ecd.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import top.xin1901.j2ecd.beans.Group;
import top.xin1901.j2ecd.beans.dbo.GroupDbO;
import top.xin1901.j2ecd.dao.GroupDao;
import top.xin1901.j2ecd.service.GroupService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author HeYunjia
 */

@Service
public class GroupServiceImpl implements GroupService {

    @Resource
    private GroupDao groupDao;

    @Override
    @Transactional
    public Group insert(Group group) {
        Date date = new Date();
        group.setGmtCreate(date);
        group.setGmtModified(date);

        GroupDbO groupDbO = group.toGroupDbO();
        int insert = groupDao.insert(groupDbO);
        if (insert != 1) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return null;
        }

        List<Long> roleIds = group.toRoleIds();
        int insertRoles = groupDao.insertRoles(groupDbO.getGroupId(), roleIds);
        if (insertRoles != roleIds.size()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return null;
        }

        return selectOne(groupDbO.getGroupId());
    }

    @Override
    public List<Group> selectAll() {
        return groupDao.selectAll();
    }

    @Override
    public Group selectOne(Long groupId) {
        return groupDao.selectOne(groupId);
    }
}
